export default{
    namespaced: true,
    state: {
        name:"购物车carts",
        carts:[]
    },
    actions: {
        ADD_TO_CART(context,payload){
            context.commit('SET_CARD',payload)
            context.commit('product/DECREASE_INVENTORY',payload,   {root:true})
        },
        // 移出购物车
        REMOVE_CART(context,payload){
            console.log(payload)
            context.commit('DECREASE_CART',payload)
            context.commit('product/ INCREASE_INVENTORY',payload, {root:true})
        }
    },
    getters: {
        
    },
    mutations: {
       LOG(state){
        console.log(state)
       } ,
    //    加入购物车
       SET_CARD(state,payload){
        //   先判断
        let target=state.carts.find(item=>item.id===payload.id)
        if(target){
             target.count++
        }else{
            // 没有 创建一个obj
            let obj={
                id:payload.id,
                title:payload.title,
                price:payload.price,
                count:1
            }
            state.carts.push(obj)
        }
       },
       DECREASE_CART(state,payload){
         // payload.count--;

        let target=state.state.carts.find(item=>item.id===payload.id)
        console.log(target);
        if(target){
            target.count--
        }
    
       if(target.count===0){
          state.carts=state.carts.filters(item=>
            item.id!=target.id)
       }

    }

  } 
}